﻿//code by Heskey0
//https://space.bilibili.com/455965619
//https://github.com/Heskey0

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Common.Extension;
using UnityEditor;
using UnityEngine;

namespace Teresa.Editor
{
    public class UIRootWindow : EditorWindow
    {
        [MenuItem("CustomTools/UI/UIRootWindow", priority = 102)]
        private static void ShowWindow()
        {
            var window = GetWindow<UIRootWindow>();
            window.titleContent = new GUIContent("UIRoot编辑器");
            window.Show();
        }

        XmlDocument _xmlDoc = new XmlDocument();
        private List<string> _layerNameList = new List<string>();
        private List<bool> _toggleList = new List<bool>();

        private void OnEnable()
        {
            _layerNameList.Clear();
            _toggleList.Clear();
            //读取xml
            string xmlPath = AppConfig.Path.Data.ConfigPath + "UIRoot.xml";

            if (!File.Exists(xmlPath))
            {
                using (FileStream fs = File.Create(xmlPath))
                {
                }

                var root = _xmlDoc.CreateElement("UIRoot");

                _xmlDoc.AppendChild(root);
                _xmlDoc.Save(xmlPath);
                DebugTools.Log($"创建UIRoot的xml文件::{xmlPath}", "orange");
            }

            try
            {
                _xmlDoc.Load(xmlPath);
                var rootNode = _xmlDoc.ChildNodes[0];

                foreach (XmlElement layer in rootNode.ChildNodes)
                {
                    _layerNameList.Add(layer.Name);
                    _toggleList.Add(false);
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }

        private void OnGUI()
        {
            EditorGUILayout.BeginVertical();

            for (int i = 0; i < _layerNameList.Count; i++)
            {
                EditorGUILayout.BeginHorizontal();
                _layerNameList[i] = EditorGUILayout.TextField(_layerNameList[i]);
                _toggleList[i] = EditorGUILayout.Toggle(_toggleList[i]);

                if (i == 0)
                {
                    EditorGUILayout.EndHorizontal();
                    continue;
                }

                int j = i;
                if (GUILayout.Button("上移"))
                {
                    var tmpName = _layerNameList[j];
                    var tmpToggle = _toggleList[j];

                    _layerNameList[j] = _layerNameList[j - 1];
                    _toggleList[j] = _toggleList[j - 1];

                    _layerNameList[j - 1] = tmpName;
                    _toggleList[j - 1] = tmpToggle;
                }

                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("+"))
            {
                _layerNameList.Add("");
                _toggleList.Add(false);
            }

            if (GUILayout.Button("删除选中的layer"))
            {
                for (int i = 0; i < _toggleList.Count; i++)
                {
                    if (_toggleList[i])
                    {
                        _layerNameList.RemoveAt(i);
                        _toggleList.RemoveAt(i);
                    }
                }
            }

            EditorGUILayout.EndHorizontal();

            if (GUILayout.Button("生成UIRoot"))
            {
                string xmlPath = AppConfig.Path.Data.ConfigPath + "UIRoot.xml";
                var rootNode = _xmlDoc.ChildNodes[0];
                rootNode.RemoveAll();
                for (int i = 0; i < _layerNameList.Count; i++)
                {
                    var layer = _xmlDoc.CreateElement(_layerNameList[i]);
                    layer.SetAttribute("priority", i.ToString());
                    rootNode.AppendChild(layer);
                    DebugTools.Log("创建layer::" + layer.Name);
                }

                _xmlDoc.Save(xmlPath);


                CreateUIRoot(_layerNameList);

                //生成Manager代码
                UIRootCodeGen.GenerateCode(_layerNameList);
            }

            EditorGUILayout.EndVertical();
        }


        private void CreateUIRoot(List<string> layerNameList)
        {
            //清空UIRoot
            if (File.Exists(AppConfig.Path.UI.UIRootPath))
            {
                File.Delete(AppConfig.Path.UI.UIRootPath);
            }
            
            //创建临时UIRoot
            GameObject uiRoot = new GameObject("UIRoot");
            for (int i = 0; i < layerNameList.Count; i++)
            {
                GameObject element = new GameObject(layerNameList[i]);
                element.SetParent(uiRoot);
            }
            GameObject uiCamera = new GameObject("UICamera");
            uiCamera.SetParent(uiRoot);
            var camera = uiCamera.AddComponent<Camera>();
            camera.clearFlags = CameraClearFlags.Depth;
            camera.cullingMask = LayerMask.NameToLayer("UI");
            camera.orthographic = true;
            camera.orthographicSize = 5;
            camera.nearClipPlane = 0.3f;
            camera.farClipPlane = 1000;
            camera.allowHDR = false;

            Selection.activeGameObject = uiRoot;
          
            
            //生成Prefab
            PrefabUtility.SaveAsPrefabAsset(uiRoot, AppConfig.Path.UI.UIRootPath.Replace("/UIRoot","/UIRoot.prefab"));
            
            GameObject.DestroyImmediate(uiRoot);
        }
    }
}